package com.shuogesha.filter;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.shuogesha.common.util.JsonResult;
import com.shuogesha.common.util.ResultCode;
import com.shuogesha.platform.Constants;
import com.shuogesha.platform.client.AuthenticationFeignClient;
import com.shuogesha.platform.client.UserFeignClient;
import com.shuogesha.platform.entity.Authentication;
import com.shuogesha.platform.entity.User;
import com.shuogesha.platform.util.CookieUtils;
import com.shuogesha.platform.util.ResponseUtils;
import com.shuogesha.platform.web.CmsUtils;

/**
 * 登录认证拦截
 * 
 * @author zhaohaiyuan
 *
 */
@Configuration
public class AdminInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {

	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		User user = null;
		Long userId = retrieveUserId(request);
		// userId如果是空
		if (userId == null) {
			String authId = request.getHeader(Constants.AUTH_KEY);
			if (StringUtils.isNotBlank(authId)) {
				Authentication auth = authenticationService.findById(authId);
				if (auth != null) {
					userId = auth.getUid();
				}
			}
		}
		if (userId != null) {
			user = userService.findById(userId);
			CmsUtils.setUser(request, user);
		}
		if (!isAuth()) {// 是否开启认证
			return true;
		}
		if (user == null) {
			ResponseUtils.renderJson(response, new JsonResult(ResultCode.INVALID_AUTHCODE, "授权认证失败", null).toString());
			return false;
		}
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		response.setHeader("Access-Control-Allow-Headers", "Access-Control");
		response.setHeader("Allow", "POST");
		return true;
	}

	/**
	 * 根据认证信息获取用户id
	 * 
	 * @param request
	 * @return
	 */
	public Long retrieveUserId(HttpServletRequest request) {
		String authId = request.getHeader("ssid");
		if (authId == null) {
			Cookie cookie = CookieUtils.getCookie(request, "ssid");
			if (cookie != null && cookie.getValue() != null) {
				authId = cookie.getValue();
			} else {
				return null;
			}
		}
		Authentication auth = authenticationService.retrieve(authId);
		if (auth == null) {
			return null;
		}
		return auth.getUid();
	}

	@Autowired
	public AuthenticationFeignClient authenticationService;
	@Autowired
	public UserFeignClient userService;
	public boolean auth = true;// 开启认证

	public boolean isAuth() {
		return auth;
	}

	public void setAuth(boolean auth) {
		this.auth = auth;
	}

}
